# -*- coding: UTF-8 -*-
from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, get_object_or_404

from django.contrib.auth.decorators import login_required

# Create your views here
from django.forms.models import model_to_dict
#
from django.http import JsonResponse
from .forms import PlatForm_Form
from .models import PlatForm

@login_required()
def platform_list(request):
    if request.method == 'POST':
        option = request.GET.get('option')
        if option == 'add':
            form = PlatForm_Form(request.POST or None)
            # 判断form是否有效
            if form.is_valid():
                # 创建实例，需要做些数据处理，暂不做保存
                instance = form.save(commit=False)
                # 将登录用户作为登记人
                instance.node_signer = request.user
                # 保存该实例
                try:
                    instance.save()
                    return JsonResponse({'msg': "successful"}, safe=False)
                except Exception as e:
                    print(e.message)
                    return JsonResponse({'msg': "failed"}, safe=False)
        elif option == 'update':
            # update
            id = request.POST.get('id')
            server = get_object_or_404(PlatForm_Form, pk=int(id))
            form = PlatForm_Form(request.POST, instance=server)
            if form.is_valid():
                server = form.save()
                server.save()
                return JsonResponse({'msg': "successful"}, safe=False)
            else:
                return JsonResponse({'msg': "failed"}, safe=False)
        elif option == 'del':
            server_id = request.POST.get("serverid")
            server_id = server_id.split('.')
            t = [int(x.strip()) for x in server_id]
            try:
                rows = PlatForm.objects.filter(id__in=t)
                rows.delete()
            except Exception as e:
                print(e.message)
                return JsonResponse({'msg': "删除失败"}, safe=False)
            return JsonResponse({'msg': "删除成功"}, safe=False)
        elif option == "query":
            server_id = request.POST.get('serverid')
            rows = PlatForm.objects.get(id=server_id)
            rows = model_to_dict(rows)
            return JsonResponse(rows, safe=False)
        elif option == "search":
            ip=request.POST.get("ip","")
            machine_room=request.POST.get("machine_room","")
            purpose=request.POST.get("purpose","")
            platform=request.POST.get("platform")
            if platform == "":
                posts = PlatForm.objects.filter(ip__icontains=ip, machine_room__icontains=machine_room,
                                              purpose__icontains=purpose)
            else:
                p_list=[int(platform)]
                posts = PlatForm.objects.filter(ip__icontains=ip, machine_room__icontains=machine_room,
                                              purpose__icontains=purpose, platform__in=p_list)

            form = PlatForm_Form
            search_form = PlatForm_Form

            return render(request, 'myauth/platform_list.html', locals())




    elif request.method == 'GET':
        form = PlatForm_Form
        search_form= PlatForm_Form
        ONE_PAGE_OF_DTAA = 0
        try:
            curpage = int(request.GET.get('curpage', '1'))
            allpage = int(request.GET.get('allpage', '1'))
            try:
                ONE_PAGE_OF_DTAA = int(request.COOKIES["pageper"])
            except Exception:
                pass
        except ValueError as e:
            print(e.message)
            curpage = 1
            allpage = 1
            pagetype = ''
            ONE_PAGE_OF_DTAA = 15

        if ONE_PAGE_OF_DTAA == 0:
            ONE_PAGE_OF_DTAA = 10
        startops = (curpage - 1) * ONE_PAGE_OF_DTAA
        endpos = startops + ONE_PAGE_OF_DTAA
        posts = PlatForm.objects.all()[startops:endpos]
        # print startops, endpos
        if curpage == 1 and allpage == 1:
            allpostcounts = PlatForm.objects.count()
            allpage = allpostcounts / ONE_PAGE_OF_DTAA
            remainpost = allpostcounts % ONE_PAGE_OF_DTAA
            if remainpost > 0:
                allpage += 1
        pagelist = range(1, allpage + 1)
        # print pagelist
        return render(request, 'myauth/platform_list.html', locals())